<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
    crossorigin="dddjs.github.io"></script>
  <script type="text/javascript">
    // API Key: P3xLGkvAHlMkLjEP6cu9zsTi
    // Secret Key: s5LWNWkx7TXCDye1M42i0CIFbMu8Dg1t
    // url:http://vop.baidu.com/server_api
    // 初始化变量

    window.getData = function (base64data, len) {
      $.ajax({
        type: 'POST',
        url: "/server_api",
        async: true, // 使用同步操作
        timeout: 50000, //超时时间：50秒
        data: {
          format: "amr",
          rate: 16000,
          channel: 1,
          cuid: 'bitor',
          token: '24.662081bcb1ab75c0328d23d3bbbad791.2592000.1546956301.282335-15105521',
          ptc: "",
          lan: 'zh',
          // url:"",
          // callback:'',
          speech: base64data,
          len: len,
        },
        success: function (res) {
          if (res.status == 1) {
            alert(res.result)
            if (res.err_no !== 0) {
              alert(res.result)
            }
          }

        },
        // processData : false,
        // dataType: 'json',
        // contentType : false,
        contentType:'application/json;charset=utf-8',
        error: function (res) {
          alert(JSON.stringify(res))
        }
      });
    }
  </script>
</head>

<body>
  <button id="record_audio">录音频</button>
  <button id="stop_audio">stop</button>
  <script>
    var record_audio = document.querySelector('#record_audio');
    var stop_audio = document.querySelector('#stop_audio');
    var audio_stream;
    var media1 = navigator.mediaDevices.getUserMedia({
      audio: true
    });
    media1.then((stream) => {
      audio_stream = stream;

    }).catch((error) => {
      alert(error)
    });
    record_audio.onclick = function () {
      record_audio.disabled = 'true';
      var mediaRecorder = new MediaRecorder(audio_stream);
      mediaRecorder.ondataavailable = function (e) {
        blob_audio = new Blob([e.data], {
          type: 'audio/amr'
        });
        //可以存为mp3格式但是本地无法播放，只有网页可以播放
      }
      mediaRecorder.start();
      mediaRecorder.onstop = function () {
        var reader = new FileReader();
        reader.readAsDataURL(blob_audio);
        reader.onloadend = function () {
          let base64data = reader.result;

          try {
            window.getData(base64data, blob_audio.size);
          } catch (error) {
            alert(error)
          }


        }
      }

      stop_audio.onclick = function () {
        record_audio.disabled = '';
        mediaRecorder.stop();
      }
    }
  </script>
</body>

</html>